/*****************************************************************************
 * img.c: GD image manipulation functions
 *****************************************************************************
 * Copyright (C) 2010 Sam Grandjean
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *****************************************************************************/

#include <stdio.h>

#include "img.h"
#include "gd.h"

gdImagePtr load_image(const char* path, const enum IMAGE_FORMAT format)
{
	gdImagePtr im = NULL;
	FILE *in;
	if ((in = fopen(path, "rb")) == NULL) {
		return NULL;
	}
	switch (format) {
		case PNG:
			im = gdImageCreateFromPng(in);
			break;
		case JPEG:
			im = gdImageCreateFromJpeg(in);
			break;
		case GIF:
			im = gdImageCreateFromGif(in);
			break;
	}
	fclose(in);
	return im;
}

int save_image(const gdImagePtr im, const char* path, const enum IMAGE_FORMAT format)
{
	FILE *out;
	if ((out = fopen(path, "wb")) == NULL) {
		return -1;
	}
	switch (format) {
		case PNG:
			gdImagePng(im, out);
			break;
		case JPEG:
			gdImageJpeg(im, out, JPEG_QUALITY);
			break;
		case GIF:
			gdImageGif(im, out);
			break;
	}
	fclose(out);
	return 0;
}

/*
gdImagePtr resize_image(const gdImagePtr src_im, const int width, const int height)
{
	gdImagePtr im;
	im = gdImageCreateTrueColor(width, height);
	gdImageCopyResampled(im, src_im, 0, 0, 0, 0, width, height, gdImageSX(src_im), gdImageSY(src_im));
	return im;
}
*/

gdImagePtr resize_image_replace(gdImagePtr src_im, const int width, const int height, const int truecolor)
{
	gdImagePtr tmp_im;
	tmp_im = gdImageCreateTrueColor(width, height);
	gdImageCopyResampled(tmp_im, src_im, 0, 0, 0, 0, width, height, gdImageSX(src_im), gdImageSY(src_im));

	gdImageDestroy(src_im);
	if (truecolor == 0) {
		src_im = gdImageCreate(width, height);
	} else {
		src_im = gdImageCreateTrueColor(width, height);
	}
	gdImageCopy(src_im, tmp_im, 0, 0, 0, 0, width, height);

	gdImageDestroy(tmp_im);
	return src_im;
}

